package com.example.stack08.stack;

/**
 * @description 链表实现的栈
 * @auther lijiewei
 * @date 2021/8/19 16:57
 */
public class LinkedListBasedStack {

    /** 栈大小. */
    private int size;
    /** 栈的顶层结点. */
    private Node top;

    /**
     * 压栈，栈中加结点
     * @param data 数据
     * @return
     * @author lijiewei
     * @date   2021/8/19 17:01
     */
    public void push(String data) {
        Node newNode = new Node(data, this.top);
        this.top = newNode;
        size++;
    }

    /**
     * 取出栈的第一个结点
     * @return
     * @author lijiewei
     * @date   2021/8/19 17:06
     */
    public Node pop() {
        if (null == top) {
            System.out.println("空栈");
            return null;
        }
        Node curNode = top;
        top = curNode.getNext();
        size--;
        return curNode;
    }

    /**
     * 返回栈顶的数据
     * @return
     * @author lijiewei
     * @date   2021/8/19 17:32
     */
    public String getTopData() {
        if (null == top) {
            return null;
        }
        return top.getData();
    }

    public int size() {
        return size;
    }

    /**
     * 清空栈
     * @return
     * @author lijiewei
     * @date   2021/8/19 17:29
     */
    public void clear() {
        top = null;
        size = 0;
    }

    /**
     * 打印栈中所有结点数据
     * @return
     * @author lijiewei
     * @date   2021/8/19 17:39
     */
    public void printAll() {
        Node curNode = top;
        while (null != curNode) {
            String data = curNode.getData();
            System.out.println(data + " ");
            curNode = curNode.getNext();
        }
        System.out.println();
    }
}
